// pages/grouping/grouping.js
import * as API_Shop from '../../api/shop.js'
import * as API_Trade from '../../api/trade.js'
import * as watch from "../../utils/watch.js";
import { Foundation } from '../../ui-utils/index.js'
const app = getApp();
let that;

Page({
  data: {
    scrollH: 0,
    currentScroll: 0,
    scrollTop: 0,
    scrollHeight: 0,
    scrollGoodsHeight: 0,
    goodsScrollTop: -200,
    cartGoodsCount: 0,

    // 1级分组
    activeType: '',
    activeTypeIndex: 0,
    typeData: [],
    // 团购商品
    goodsData: [],
    // 商品分页
    playId: '',
    page_no: 1,
    page_size: 10,
    page_count: 0,
    // 上拉加载
    loadText: '～上拉加载更多～',
    showNextCat: false,
    // 团购购物车
    cartData: []
  },
  onLoad: function (options) {
    that = this;
    wx.getSystemInfo({
      success: function (res) {
        let query = wx.createSelectorQuery();
        query.select('.search').boundingClientRect();
        query.exec(response => {
          that.setData({
            scrollHeight: res.windowHeight - response[0].height + 'px',
            scrollGoodsHeight: res.windowHeight - response[0].height
          });
        });
      }
    });
    let _id = options && options.grouping_id ? parseInt(options.grouping_id) : '';
    this.getCommunityCats(_id);
    watch.setWatcher(this); // 启用数据监听
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {
    this.setData({
      showNextCat: false
    });
    this.getAllCount();
    // 获取团购购物车列表信息
    let shetuan_cart = await app.getTuanCart();
    this.setData({
      cartData: shetuan_cart
    });
  },
  watch:{
    cartData: function(newVal){
      this.cartContrast();
    }
  },
  //获取购物车数量
  getAllCount() {
    let { city } = app.globalData.locationData;
    API_Trade.getCartCount(city).then(res => {
      this.setData({ cartGoodsCount: res.TOTAL_CART || 0 })
    });
  },
  // 获取当前位置社区团购店铺分组列表数据
  getCommunityCats: async function(_id) {
    const _locationData = app.globalData.locationData;
    let _params = {
      'lat': _locationData.latitude,
      'lng': _locationData.longitude
    };
    let typeData = await API_Shop.getCommunityCats(_params) || [];
    let { activeType, activeTypeIndex } = this.data;
    let _useIndex = typeData.findIndex(item => (_id && item.shop_cat_id === _id));
    activeTypeIndex = _useIndex < 0 ? 0 : _useIndex;
    let _useType = typeData[activeTypeIndex];
    activeType = _useType.shop_cat_id || '';
    this.setData({
      activeType,
      activeTypeIndex,
      typeData,
      page_no: 1,
      page_count: 0
    });
    this.getShetuanGoods();
  },
  // 获取分组商品
  async getShetuanGoods () {
    if (this.data.showNextCat) {
      this.setData({
        showNextCat: false
      });
    };
    let { activeType, activeTypeIndex, typeData, goodsData, page_no, page_size, loadText } = this.data;
    goodsData = page_no === 1 ? [] : goodsData;
    // 位置信息
    let { latitude, longitude } = app.globalData.locationData;
    let _params = {
      page_no,
      page_size,
      shop_cat_id: activeType,
      user_lat: latitude,
      user_lng: longitude
    };
    API_Shop.getShetuanGoods(_params).then(res => {
      let { data, data_total, page_size, page_count } = res;
      page_count = Math.ceil(data_total / page_size);
      let _list = data || [];
      _list.forEach(item => {
        item.shetuan_price = Foundation.formatPrice(item.shetuan_price);
        item.priceInt = item.shetuan_price ? item.shetuan_price.split('.')[0] : '0';
        item.pricePoint = item.shetuan_price ? item.shetuan_price.split('.')[1] : '00';
      });
      _list = goodsData.concat(data);
      if (page_count > page_no) {
        loadText = '～上拉加载更多～';
      } else {
        loadText = typeData.length <= activeTypeIndex + 1 ? '~已经到底了~' : '~上拉查看下一分组~';
      };
      if (page_no === 1) {
        this.setData({
          goodsScrollTop: 0
        });
      };
      this.setData({
        goodsData: _list,
        page_count,
        loadText
      });
    });
  },
  // 1级切换分组
  switchType(e) {
    let { useid, index } = e.currentTarget.dataset;
    let { activeType, activeTypeIndex } = this.data;
    if (activeType !== useid) {
      activeType = useid;
      activeTypeIndex = index;
      this.setData({
        activeType,
        activeTypeIndex,
        page_no: 1,
        page_count: 0
      });
      this.getShetuanGoods();
    };
  },
  // 图片跳转商品详情页面 
  getHref(e) {
    const { video, useid, sku } = e.currentTarget.dataset;
    if (video) {
      return;
    };
    wx.navigateTo({
      url: `/pages/goods/goods?goods_id=${useid}&sku_id=${sku}`
    });
  },
  // 视屏显示
  playVideo: function (e) {
    const { id, index } = e.currentTarget.dataset;
    let { goodsData, playId } = this.data;
    goodsData[index].showVideo = true;
    // 暂停当前播放的视频
    if (playId) {
      let currentVideo = wx.createVideoContext(playId, this);
      currentVideo.pause();
    };
    let videoplay = wx.createVideoContext(id, this);
    videoplay.play();
    this.setData({
      goodsData,
      playId: id
    });
  },
  // 视屏继续播放
  playContinue: function (e) {
    const { id } = e.currentTarget.dataset;
    let { playId } = this.data;
    // 暂停当前播放的视频
    if (id !== playId) {
      let currentVideo = wx.createVideoContext(playId, this);
      currentVideo.pause();
      this.setData({
        playId: id
      });
    };
  },
  // 首次加入购物车
  async addCart(e) {
    let _isLogin = await app.isLogin();
    if (!_isLogin) { return };
    const { index } = e.currentTarget.dataset;
    let { goodsData } = this.data;
    const { sku_id, shetuan_id } = goodsData[index];
    const _buyNum = 1; // 数量
    API_Trade.addToCart(sku_id, _buyNum, shetuan_id).then(response => {
      goodsData[index].cart_num = 1;
      this.setData({
        goodsData
      });
    });
  },
  // 更新商品数量
  async handleUpdateSkuNum(e) {
    const { index } = e.currentTarget.dataset;
    const { goodsData } = this.data;
    const { sku_id, cart_num, enable_quantity } = goodsData[index];
    const useParams = {
      index,
      sku_id: sku_id
    };
    const symbol = e.currentTarget.dataset.symbol;
    if (!symbol || typeof symbol !== 'string') {
      if (!e.detail.value) return
      let _num = parseInt(e.detail.value)
      if (isNaN(_num) || _num < 1) {
        wx.showToast({ title: '输入格式有误，请输入正整数', icon: 'none' })
        return
      }
      if (_num >= enable_quantity) {
        wx.showToast({ title: '超过最大库存', icon: 'none' })
        return
      };
      useParams.num = _num;
      this.updateSkuNum(useParams);
    } else {
      if (symbol === '-' && cart_num < 2) {
        wx.showModal({
          title: '提示',
          content: '确定要删除此商品吗?',
          confirmColor: '#f42424',
          success(res) {
            /** 删除 */
            if (res.confirm) {
              API_Trade.deleteSkuItem(sku_id, 'SHETUAN_CART').then(_ => {
                //更新购物车数量
                that.getAllCount();
                const { goodsData } = that.data;
                goodsData[index].cart_num = 0;
                that.setData({
                  goodsData
                });
              }).catch()
            }
          }
        });
        return;
      };
      if (symbol === '+' && cart_num >= enable_quantity) {
        wx.showToast({ title: '超过最大库存', icon: 'none' })
        return
      };
      let _num = symbol === '+' ? cart_num + 1 : cart_num - 1;
      useParams.num = _num;
      this.updateSkuNum(useParams);
    };
  },
  // 更新sku数据
  updateSkuNum(params) {
    setTimeout(() => {
      API_Trade.updateSkuNum(params.sku_id, params.num, 'SHETUAN_CART').then(_ => {
        //更新购物车数量
        this.getAllCount();
        const { goodsData } = this.data;
        goodsData[params.index].cart_num = params.num;
        this.setData({
          goodsData
        });
      }).catch()
    }, 200)
  },
  // 进入购物车
  goCart() {
    wx.switchTab({ url: '/pages/cart/cart' })
  },
  // 加载下级分类
  loadmore() {
    // 上拉查看下一分组
    let { page_no, page_count } = this.data;
    this.setData({ 
      page_no: page_no += 1
    });
    if (page_count >= page_no) {
      this.getShetuanGoods();
    } else {
      let { activeTypeIndex, typeData, loadText } = this.data;
      if (typeData.length > activeTypeIndex + 1) {
        if (loadText === '~上拉查看下一分组~') {
          setTimeout(() => this.setData({
            showNextCat: true
          }), 1000);
          return;
        };
      } else {
        this.setData({
          loadText: '~已经到底了~'
        });
      };
    };
  },
  scroll(e) {
    const { scrollHeight, scrollTop } = e.detail;
    this.setData({
      scrollH: scrollHeight,
      currentScroll: scrollTop
    });
  },
  // 开始滑动事件
  touchS: function (e) {
    if (this.data.showNextCat && e.touches.length == 1) {
      this.setData({
        //设置触摸起始点垂直方向位置 
        startY: e.touches[0].clientY
      });
    };
  },
  // 滑动中事件
  touchE: function (e) {
    if (this.data.showNextCat && e.changedTouches.length == 1) {
      //手指移动结束后垂直位置 
      let endY = e.changedTouches[0].clientY;
      //触摸开始与结束，手指移动的垂直距离 
      let disY = this.data.startY - endY;
      if (disY > 0) {
        let { activeType, activeTypeIndex, typeData, loadText, currentScroll, showNextCat } = this.data;
        activeTypeIndex ++;
        activeType = typeData[activeTypeIndex].shop_cat_id;
        this.setData({
          activeTypeIndex,
          activeType,
          goodsData: [],
          page_no: 1,
          page_count: 0
        });
        this.getShetuanGoods();
      };
    };
  },
  // 对比购物车更新商品的数量
  cartContrast: async function() {
    let { goodsData } = this.data;
    if (goodsData && goodsData.length) {
      let _newUseData = await app.cartContrast(goodsData);
      this.setData({
        goodsData: _newUseData
      });
    };
  }
})